package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserLoginDTO;
import cn.tedu._05weibo.pojo.dto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpSession httpSession;

    //    1/注册功能
    @PostMapping("reg")
    public int reg( @RequestBody UserRegDTO userRegDTO){
        /**
         * 业务逻辑
         * 1.接收客户端数据
         * 2.校验数据的合法性
         * 3.检验是否被占用【SELECT 接口】
         *      占用，返回2
         *      未占用，插入数据【INSERT 接口】，返回1
         */
        System.out.println("userRegDTO = " + userRegDTO);

//     确认是否被占用
       UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());

       if(userVO != null){
           return 2;
       }
       //未被占用，插入信息
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insertUser(user);


       return 1;
    }

//    2/登录功能
    @PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDTO ,HttpSession session){
     UserVO userVO =   userMapper.selectByUsername(userLoginDTO.getUsername());
    if(userVO == null){
        return 3;
    }
    if(userVO.getPassword().equals(userLoginDTO.getPassword())){
       session.setAttribute("user",userVO);
        return 1;
    }
        return 2;
    }

//    3/获取当前用户
    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        UserVO  userVO = (UserVO) session.getAttribute("user");
        return  userVO;
    }

    @GetMapping("logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }

}
